package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IRestaurantSettlementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author wlmes
 * @date 2023-12-18
 */
@Service
public class RestaurantSettlementServiceImpl implements IRestaurantSettlementService {
    @Resource
    private RestaurantSettlementMapper restaurantSettlementMapper;

    @Resource
    RestaurantCustomerMapper customerMapper;

    @Resource
    StoreInDetailMapper storeInDetailMapper;

    @Resource
    RestaurantBalanceDetailMapper restaurantBalanceDetailMapper;

    @Resource
    VendorSettlementMapper vendorSettlementMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public RestaurantSettlement selectMoneySettlementById(Long id) {
        return restaurantSettlementMapper.selectMoneySettlementById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param moneySettlement 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<RestaurantSettlement> selectMoneySettlementList(RestaurantSettlement moneySettlement) {
        return restaurantSettlementMapper.selectMoneySettlementList(moneySettlement);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param moneySettlement 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertMoneySettlement(RestaurantSettlement moneySettlement) {
        if (StringUtils.isNull(moneySettlement)) {
            throw new BaseException("新增【请填写功能名称】失败！");
        }
        moneySettlement.setCreateTime(DateUtils.getNowDate());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        moneySettlement.setCreateBy(String.valueOf(user.getUserId()));
        return restaurantSettlementMapper.insertMoneySettlement(moneySettlement);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param moneySettlement 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateMoneySettlement(RestaurantSettlement moneySettlement) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        moneySettlement.setUpdateBy(String.valueOf(user.getUserId()));
        return restaurantSettlementMapper.updateMoneySettlement(moneySettlement);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteMoneySettlementByIds(Long[] ids) {
        if (StringUtils.isNull(ids)) {
            throw new BaseException("需要删除的【请填写功能名称】ID为空！");
        }
        return restaurantSettlementMapper.deleteMoneySettlementByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteMoneySettlementById(Long id) {
        if (StringUtils.isNull(id)) {
            throw new BaseException("需要删除的【请填写功能名称】ID为空！");
        }
        return restaurantSettlementMapper.deleteMoneySettlementById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveNewRestaurantSettlement(RestaurantSettlement restaurantSettlement) {
        String area = "";
        if (restaurantSettlement != null && StringUtils.isNotBlank(restaurantSettlement.getArea())) {
            area = restaurantSettlement.getArea();
        }
        if (StringUtils.isBlank(area)) {
            area = SecurityUtils.getUserLocation();
        }
        if (StringUtils.isBlank(area) || !area.equals("全部")) {
            throw new BaseException("登录用户的园区不为全部,无法新增");
        }

        restaurantSettlement.setArea(area);

        //当前日期
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //计算盘点账期
        //当前月 日
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        int day = localDate.getDayOfMonth();
        String panDate = "";
        String panDateStart = "";
        String panDateEnd = "";

        if (StringUtils.isNotBlank(restaurantSettlement.getSettlementTime())) {
            panDate = restaurantSettlement.getSettlementTime() + "-25";
            int a = Integer.valueOf(panDate.split("-")[1]);
            if (a == 1) {
                panDateStart = (Integer.valueOf(panDate.split("-")[0]) - 1) + "-12-26" + " 00:00:00";
            } else {
                panDateStart = Integer.valueOf(panDate.split("-")[0]) + "-" + (Integer.valueOf(panDate.split("-")[1]) - 1) + "-26" + " 00:00:00";
            }
            panDateEnd = panDate + " 23:59:59";
        } else {
            if (day > 25) {
                //本月25
                panDate = month + "月" + "25日";
            } else {
                //上月25
                panDate = month - 1 == 0 ? "12" : month - 1 + "月" + "25日";
            }

            if (month == 1) {
                panDateEnd = year + "-" + month + "-" + "25" + " 23:59:59";//先赋值在减

                year = year - 1;
                month = 12;
                panDateStart = year + "-" + month + "-" + "25" + " 00:00:00";
            } else {
                panDateEnd = year + "-" + month + "-" + "25" + " 23:59:59";//先赋值在减

                panDateStart = year + "-" + (month - 1) + "-" + "25" + " 00:00:00";
            }
        }


        BigDecimal staffUseTotal = BigDecimal.ZERO;//本期总收入
        BigDecimal householdUseTotal = BigDecimal.ZERO;//本期总支出-需要查询本期总供应商结算金额
//        BigDecimal staffCaseTotal = BigDecimal.ZERO;
        BigDecimal householdCaseTotal = BigDecimal.ZERO;//员工账户余额总计
        BigDecimal staffCardTotal = BigDecimal.ZERO;//住户账户余额总计
//        BigDecimal householdCardTotal = BigDecimal.ZERO;
//        BigDecimal staffBuckleTotal = BigDecimal.ZERO;
//        BigDecimal householdBuckleTotal = BigDecimal.ZERO;


        //查询消费明细
        RestaurantBalanceDetail query = new RestaurantBalanceDetail();
        query.setStartDate(panDateStart);
        query.setEndDate(panDateEnd);
        List<RestaurantBalanceDetail> balanceDetails = restaurantBalanceDetailMapper.selectRestaurantBalanceDetailList(query);
        for (RestaurantBalanceDetail restaurantBalanceDetail : balanceDetails) {
            staffUseTotal = staffUseTotal.add(restaurantBalanceDetail.getBalance() == null ? BigDecimal.ZERO : restaurantBalanceDetail.getBalance());
        }

//        //查询这个时间段所有的入库单-已确认的
//        List<VendorSettlementSearch> outs = storeInDetailMapper.selectSettlementListByDate(panDateStart,panDateEnd);
        VendorSettlement vsearch = new VendorSettlement();
        vsearch.setSettlementTime(panDate);
        List<VendorSettlement> vendorSettlements = vendorSettlementMapper.selectVendorSettlementList(vsearch);
        if (!CollectionUtils.isEmpty(vendorSettlements)) {
            throw new BaseException("未查询到当期的供应商结算记录，无法计算总支出，请先进行供应商结算" + panDate);
        }
        for (VendorSettlement vendorSettlement : vendorSettlements) {
            householdUseTotal = householdUseTotal.add(vendorSettlement.getMoney() == null ? BigDecimal.ZERO : vendorSettlement.getMoney());
        }

        //查询余额
        List<RestaurantCustomer> customerList = customerMapper.selectRestaurantCustomerList(new RestaurantCustomer());
        for (RestaurantCustomer restaurantCustomer : customerList) {
            if (StringUtils.isNotBlank(restaurantCustomer.getLocation()) && (restaurantCustomer.getLocation().equals("一区") || restaurantCustomer.getLocation().equals("二区"))) {
                //员工
                householdCaseTotal = householdCaseTotal.add(restaurantCustomer.getBalance() == null ? BigDecimal.ZERO : restaurantCustomer.getBalance());
            } else {
                //住户
                staffCardTotal = staffCardTotal.add(restaurantCustomer.getBalance() == null ? BigDecimal.ZERO : restaurantCustomer.getBalance());
            }
        }

        restaurantSettlement.setStaffUseTotal(staffUseTotal);//本期总收入
        restaurantSettlement.setHouseholdUseTotal(householdUseTotal);//本期总支出-需要查询本期总供应商结算金额
        restaurantSettlement.setStaffCaseTotal(staffUseTotal.subtract(householdUseTotal));//本期营收余额
        restaurantSettlement.setHouseholdCaseTotal(householdCaseTotal);//员工账户余额总计
        restaurantSettlement.setStaffCardTotal(staffCardTotal);//住户账户余额总计

//        restaurantSettlement.setHouseholdCardTotal(householdCardTotal);
//        restaurantSettlement.setStaffBuckleTotal(staffBuckleTotal);
//        restaurantSettlement.setHouseholdBuckleTotal(householdBuckleTotal);
        restaurantSettlement.setSettlementTime(panDate);
        restaurantSettlement.setCreateBy(SecurityUtils.getNickName());
        restaurantSettlement.setCreateTime(new Date());
        restaurantSettlement.setBusinessNum(BaseController.createBusinessNum("RSD"));

        //去重
        RestaurantSettlement settlement = new RestaurantSettlement();
        settlement.setSettlementTime(restaurantSettlement.getSettlementTime());
        List<RestaurantSettlement> restaurantSettlements = restaurantSettlementMapper.selectMoneySettlementList(settlement);
        if (!CollectionUtils.isEmpty(restaurantSettlements)) {
            throw new BaseException("该结算日期已存在结算单据,请勿重复添加");
        }

        restaurantSettlementMapper.insertMoneySettlement(restaurantSettlement);
    }
}
